package com.help10000.rms.mvp.presenter

import android.util.Log
import android.widget.Toast
import com.amir.common.api.ApiContents
import com.amir.common.api.CustomObserver
import com.amir.common.api.upload.FileUploadObserver
import com.amir.common.beans.BaseResult
import com.amir.common.beans.FileEntity
import com.amir.common.beans.ReportEntity
import com.amir.common.beans.ReportRepairInfo
import com.amir.common.mvp.model.Model
import com.amir.common.mvp.presenter.BasePresenter
import com.amir.common.utils.Constant
import com.amir.common.utils.LogUtils
import com.amir.common.utils.SPUtils
import com.amir.common.utils.ToastUtil
import com.amir.common.utils.Utils
import com.help10000.kottlinbaselib.api.upload.UploadFileRequestBody
import com.help10000.rms.mvp.view.ReportView
import com.help10000.rms.ui.activitys.ReportOrderActivity
import com.help10000.rms.ui.utils.ImageCompressor
import com.help10000.rms.utils.LocationManager
import io.reactivex.android.schedulers.AndroidSchedulers
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.MultipartBody
import okhttp3.ResponseBody
import java.io.File
import java.net.URLEncoder

class ReportPresenter(view: ReportView) : BasePresenter<ReportView>(view) {

    //完工上报加载
    fun repairDoneInit(repairId: String) {
        val AccessToken = SPUtils.getString(Constant.AccessToken)
        val repairDoneInit = Model.getServer().RepairDoneInit(AccessToken, repairId)
        Model.getObservable(repairDoneInit, object : CustomObserver<ReportEntity>(mvpView) {
            override fun success(t: ReportEntity) {
                mvpView?.descSuccess(t.data)
            }
        })
    }

    /***
     * 带实时定位的提交方法
     */
    fun save(
        activity:ReportOrderActivity,
        repairId: String,
        data: ReportRepairInfo,
        custType: String,
        repairDescr: String,
        callPhotos: String,
        type: Int//0暂存，1 完工上报
    ) {
        // 启动协程获取实时定位
        CoroutineScope(Dispatchers.IO).launch {
            val (lat, lng) = LocationManager.getLocation(activity)
            Log.d("完工上报定位", "获取到经纬度：lat=$lat, lng=$lng")
            // 切换到主线程处理定位结果
            withContext(Dispatchers.Main) {
                mvpView?.dismissLoading()
                Log.e("执行1","执行1")


                // 继续执行提交逻辑
                submitWithLocation(
                    repairId = repairId,
                    data = data,
                    custType = custType,
                    repairDescr = repairDescr,
                    callPhotos = callPhotos,
                    type = type,
                    lat = lat,
                    lng = lng
                )
            }
        }
    }

    /**
     * 使用实时获取的经纬度提交数据
     */
    private fun submitWithLocation(
        repairId: String,
        data: ReportRepairInfo,
        custType: String,
        repairDescr: String,
        callPhotos: String,
        type: Int,
        lat: String,
        lng: String
    ) {
        val AccessToken = SPUtils.getString(Constant.AccessToken)
        Log.d("坐标传递", "submitWithLocation中：lat=$lat, lng=$lng")
        // 构建请求（使用实时获取的经纬度）
        val saveOrder = Model.getServer().repairDone(
            url = if (type == 0) ApiContents.RepairDone else ApiContents.RepairDoneSave,
            accessToken = AccessToken,
            repairId = repairId,
            revenue01 = data.Revenue01,
            revenue02 = data.Revenue02,
            revenue03 = data.Revenue03,
            revenue04 = data.Revenue04,
            revenue05 = data.Revenue05,
            revenue01Name = data.Revenue01Name,
            revenue02Name = data.Revenue02Name,
            revenue03Name = data.Revenue03Name,
            revenue04Name = data.Revenue04Name,
            revenue05Name = data.Revenue05Name,
            expense01 = data.Expense01,
            expense02 = data.Expense02,
            expense03 = data.Expense03,
            expense04 = data.Expense04,
            expense05 = data.Expense05,
            expense01Name = data.Expense01Name,
            expense02Name = data.Expense02Name,
            expense03Name = data.Expense03Name,
            expense04Name = data.Expense04Name,
            expense05Name = data.Expense05Name,
            custType = custType,
            repairDescr = repairDescr,
            callPhotos = callPhotos,
            latitude = lat,
            longitude = lng,
            remark2 = data.Remark2,
            remark3 = data.Remark3
        )

        Model.getObservable(saveOrder, object : CustomObserver<BaseResult>(mvpView) {
            override fun success(t: BaseResult) {
                if (type == 0) {
                    ToastUtil.show("完工上报成功")
                } else {
                    ToastUtil.show("暂存成功")
                }
                mvpView?.saveSuccess()
            }

            override fun onError(e: Throwable) {
                super.onError(e)
                mvpView?.dismissLoading()
                ToastUtil.show("提交失败：${e.message}")
            }
        })
    }

    // 文件上传逻辑（保持不变）
    var index = 0
    var fileList = mutableListOf<String>()
    fun upFile(list: MutableList<String>, type: Int) {
        if (index >= list.size) {
            mvpView?.dismissLoading()
            mvpView?.fileUploadSuccess(fileList, type)
            return
        }

        val fileUrl = list[index]
        if (!fileUrl.startsWith("file")) {
            index++
            fileList.add(fileUrl)
            upFile(list, type)
            return
        }

        val originFile = File(fileUrl.removePrefix("file://"))
        val accessToken = SPUtils.getString(Constant.AccessToken)

        ImageCompressor.compressAsync(context = Utils.getContext(), sourceFile = originFile)
            .onErrorReturn { originFile }
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({ compressedFile ->
                val requestBody = UploadFileRequestBody(compressedFile, mFileUploadObserver)
                val part = MultipartBody.Part.createFormData(
                    "file",
                    URLEncoder.encode(compressedFile.name, "utf-8"),
                    requestBody
                )
                val uploadCall = Model.getServer().UploadFile(accessToken, part)

                Model.getObservable(uploadCall, object : CustomObserver<FileEntity>(mvpView) {
                    override fun success(t: FileEntity) {
                        fileList.add(t.FileName)
                        index++
                        upFile(list, type)
                    }

                    override fun onError(e: Throwable) {
                        super.onError(e)
                        mvpView?.dismissLoading()
                    }
                })
            }, { error ->
                LogUtils.I("ReportPresenter", "图片压缩失败: ${error.message}")
                index++
                upFile(list, type)
            })
    }

    private val mFileUploadObserver = object : FileUploadObserver<ResponseBody>(mvpView) {
        override fun onUpLoadSuccess(t: ResponseBody) {}
        override fun onUpLoadFail(e: Throwable) {}
        override fun onProgress(progress: Int) {}
    }
}